/**
 * 
 */
package client;

import java.util.HashMap;
import java.util.Scanner;

/**
 * @author Sefverl
 *
 */
public class ClientMenu 
{
	DnDClient client = new DnDClient();
	Scanner readerMenu = new Scanner(System.in);
	Scanner readerString = new Scanner(System.in);
	Scanner readerInt = new Scanner(System.in);
	private HashMap<Integer,MenuItem> map = new HashMap<Integer, MenuItem>();
	
	int i = 1;
	
	public ClientMenu()
	{
		initMap();
		initMenu();
		while(i != -1)
		{
			getData();
		}
		
	}
	
	private void initMenu()
	{
		System.out.println("DnD Client Menu\n\n");
		int enums = 1;
		
		for(MenuItem item : MenuItem.values())
		{
			System.out.println(enums+" : "+item);
			enums++;
		}
	}
	
	private void initMap()
	{
		map.clear();
		
		for(int i = 0; i<MenuItem.values().length; i++)
		{
			map.put(i+1, MenuItem.values()[i]);
		}
		
		System.out.println(map);
	}
	
	/**
	 * Execute user's selection
	 */
	private void getData()
	{
		int choice = readerMenu.nextInt();
		
		if(map.containsKey(choice)) 
		{
			handleCommand(map.get(choice));
		}
		else
		{
			System.out.println("Invalid choice");
		}
		
		initMenu();
	}
	
		
	private void handleCommand(MenuItem choice)
	{
		switch(choice)
		{
		case CONNECT:
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					client.start();
				}
			}).start();
			break;
		case CHNG_IP:
			client.setServerIP(getString("Enter IP"));
			break;
		case CHNG_PORT:
			client.setPort(getInt("Enter Port number"));
			break;
		case SEND:
			String msg = getString("Enter message");
			client.sendMessage(msg);
			break;
		case SEND_AUTH:
			client.sendAuthRequest();
			break;
		case CLOSE:
			if(showConfirmPrompt() == 1) client.disconnect();
			break;
		case SET_NAME:
			String value = getString("Enter name");
			client.setName(value);
			break;
		case QUIT:
			System.exit(0);
			break;
		}			
	}
	
	private String getString(String prompt)
	{	
		System.out.println(prompt);
		String value = readerString.nextLine();
		return value;
	}
	
	private String getString()
	{		
		String value = readerString.nextLine();
		return value;
	}
	
	private int getInt()
	{
		int value = readerInt.nextInt();
		return value;
	}
	
	private int getInt(String prompt)
	{
		System.out.println(prompt);
		int value = readerInt.nextInt();
		return value;
	}
	
	private int showConfirmPrompt()
	{
		System.out.println("Are you sure you want to proceed?\n");
		System.out.println("1: yup");
		System.out.println("2: nope\n");
		
		int choice = getInt("Enter 1 or 2");
		
		if(choice == 1) return 1;
		
		return -1;
	}

	public static void main(String[] args)
	{
		new ClientMenu();
	}

}